package com.iotek.ssm.controller;

import com.iotek.ssm.pojo.*;
import com.iotek.ssm.service.*;
import com.iotek.ssm.util.Util;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.management.relation.RelationSupportMBean;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.xml.ws.RequestWrapper;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/admin")
public class ManagerController {
    private static final String FORWARD = "forward:";
    private static final String REDIRECT = "redirect:";

    @Autowired
    private ManagerService managerService;

    @Autowired
    private UserService userService;

    @Autowired
    private SectionService sectionService;

    @Autowired
    private ApplyService applyService;

    @Autowired
    private TrainService trainService;

    @Autowired
    private Util util;

    //ajax检测登录页面用户名是否可用
    @RequestMapping("/checkName")
    @ResponseBody
    public int checkName(String name) {
        System.out.println("**********************name=" + name);
        try {
            Manager manager = managerService.findByName(name);
            if (manager != null)
                return 1;
            return 0;
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }

    //管理员登录
    @RequestMapping("/login")
    public String login(Model model, HttpSession session, HttpServletRequest req, String name, String password) {
        System.out.println("**********name=" + name + "***********password=" + password);
        try {
            Manager manager = managerService.findByName(name);
            if (manager != null && manager.getPassword().equals(password)) {
                //登陆成功，设置跳转信息
                util.setJumpDetails(model, "登录成功！", "进入管理主页", "../admin/managePageJump", 3);
                session.setAttribute("manager", manager);
//                return FORWARD + "../jumpPage.jsp";
                return "jumpPage";
            }
            model.addAttribute("error", "账号或密码错误，请重试！");
//            return FORWARD + "../admin/login.jsp";
            return "admin/login";
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("error", "系统异常，请稍后重试！");
//            return FORWARD + "admin/login.jsp";
            return "admin/login";
        }
    }

    //管理员登录进行身份验证进行页面跳转
    @RequestMapping("/managePageJump")
    public String managePageJump(Model model, HttpSession session, HttpServletRequest request) {
        Manager manager = (Manager) session.getAttribute("manager");
        //进行权限分发
        if (manager.getSection().getId() == 0) {  //超级管理员
            model.addAttribute("applyNotLook", util.getApplyNotLook());
            return "admin/backStage";
        }
        //部门管理员
        getSectionMessage(model, session, request, "");
//        model.addAttribute("entryTables",findEntryList(manager));
        return "admin/sectionChiefPage";
    }
//    @RequestMapping("/goBackStage")
//    public String goBackStage(Model model) {
//        //查询条件：未查看的应聘信息
//
//    }
//
//    @RequestMapping("/goSectionChiefPage")
//    public String goSectionChiefPage(Model model, HttpSession session, HttpServletRequest request) {
//
//    }


    //已安排未面试的
//    @ModelAttribute("applyNotInterview")
//    public List<ApplySheet> applyNotInterview( HttpSession session){
//        Manager manager = (Manager) session.getAttribute("manager");
//        System.out.println("applyNotInterview-----------"+manager.toString());
//        List<ApplySheet> applySheets = null;
//        Section section = manager.getSection();
//        if (section != null) {
//            ApplySheetQueryVo asq = new ApplySheetQueryVo();
//            asq.setSectionId(section.getId());               //条件：部门编号
//            asq.setArranged(1);                              //条件：已安排面试
//            asq.setIsInterview(0);                           //条件：未面试
//            try {
//                applySheets = applyService.findApplyList(asq);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//        return applySheets;
//    }

    // 获取部门列表
    @ModelAttribute("sections")
    public List<Section> sections() {
        List<Section> sections = null;
        try {
            sections = sectionService.findSections();
        } catch (Exception e) {
            e.printStackTrace();
        }
//        session.setAttribute("sections",sections);
        return sections;
    }

    //获取职位列表
    @RequestMapping("/positions")
    @ResponseBody
    public List<Position> positions(Integer sId) {
//        session.setAttribute("positions",positions);
        return util.getPositions(sId);
    }

    //进入培训管理
    @RequestMapping("/goTrainManage")
    public String goTrainManage(Model model, HttpServletRequest request, HttpSession session) {
        Manager manager = (Manager) session.getAttribute("manager");
        Section section = manager.getSection();
        model.addAttribute("trains", trains(request, section));
        return "admin/trainManage";
    }

    //查看应聘信息详情  即简历详情
    @RequestMapping("/goResumeDetail")
    public String goResumeDetail(@RequestParam("uId") Integer userId, @RequestParam("aId") Integer applyId, Model model) {
        ApplySheet applySheet = new ApplySheet();
        applySheet.setId(applyId);
        applySheet.setLooked(1);
        try {
            applyService.updateApply(applySheet);
        } catch (Exception e) {
            e.printStackTrace();
        }
        model.addAttribute("resumeDetail", getResume(userId));
        model.addAttribute("applyId", applyId);
        return "admin/resumeDetail";
    }

    //进入消息管理
    @RequestMapping("/goMessageManage")
    public String goMessageManage(Model model, HttpSession session, HttpServletRequest request) {
        getSectionMessage(model, session, request, "");
        List<PositionLevel> levelList = null;
        try {
            levelList = sectionService.getLevelList();
        } catch (Exception e) {
            e.printStackTrace();
        }
        model.addAttribute("levelList", levelList);
        return "admin/messageManage";
    }

    //部门管理员获取部门消息
    public void getSectionMessage(Model model, HttpSession session, HttpServletRequest request, String targetPage) {
        Manager manager = (Manager) session.getAttribute("manager");
        System.out.println(manager.toString());
        List<ApplySheet> applySheets = null;
        Section section = manager.getSection();
        if (section != null) {
            ApplySheetQueryVo asq = new ApplySheetQueryVo();
            asq.setSectionId(section.getId());               //条件：部门编号
            asq.setArranged(1);                              //条件：已安排面试
            asq.setIsInterview(0);                           //条件：未面试

            try {
                applySheets = applyService.findApplyList(asq);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        model.addAttribute("applyNotInterview", applySheets);
        model.addAttribute("trains", trains(request, section));
//        return targetPage;
    }

    //未查看的培训
//    @ModelAttribute("trains")
    public List<Train> trains(HttpServletRequest request, Section section) {
        String url = request.getRequestURL().toString();
        Integer sId = section.getId();
        List<Train> trains = null;
        CustomQueryVo cqv = new CustomQueryVo();
        if (sId != 0) {
            cqv.setSectionId(sId);
            if (url.contains("goMessageManage"))
                cqv.setDate(new Date());        //如果是进入通知管理就查询未举行的
            else{
                cqv.setLooked(0);
                cqv.setDate(new Date());       //如果是进入首页查询未查看且未举行的培训
            }
        }
//        else
//            cqv.setDate(new Date());

        try {
            trains = trainService.findTrainList(cqv);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("trains = " + trains);
        return trains;
    }

    //由用户id获取简历信息
    @RequestMapping("/getResume")
    @ResponseBody
    public Resume getResume(Integer uId) {
        User user = new User();
        user.setId(uId);
        Resume resume = null;
        try {
            resume = userService.findResume(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resume;
    }

    //进入员工管理
    @RequestMapping("/goEmployeeManage")
    public String goEmployeeManage() {
        return "admin/employeeManage";
    }

    //员工被应聘入职
    @RequestMapping("/addEmployee")
    @ResponseBody
    public Integer addEmployee(Integer uId, Integer aId, Integer lId, Integer rId) {
        User user = new User();
        user.setId(uId);
        ApplySheet applySheet = new ApplySheet();
        applySheet.setId(aId);
        EntryTable entryTable = new EntryTable();
        Resume resume = new Resume();
        resume.setId(rId);
        PositionLevel level = new PositionLevel();
        level.setId(lId);
        entryTable.setResume(resume);
        entryTable.setPositionLevel(level);
        EmployeeStatus employeeStatus = new EmployeeStatus();
        employeeStatus.setResume(resume);
        try {
            managerService.addEmployee(user, applySheet, entryTable, employeeStatus);
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    //员工未被应聘
    @RequestMapping("/notEmployee")
    @ResponseBody
    public Integer notEmploy(Integer uId, Integer aId) {
        try {
            managerService.notEmploy(uId, aId);
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    //获取员工详情
    @RequestMapping("/getEmployee")
    @ResponseBody
    public EntryTable getEmployee(CustomQueryVo customQueryVo) {
        EntryTable employee = null;
        try {
            employee = managerService.getEmployee(customQueryVo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return employee;
    }

    //添加奖惩信息
    @RequestMapping("/addRP")
    @ResponseBody
    public int addRP(RewardPunishment rewardPunishment) {
        try {
            managerService.addRP(rewardPunishment);
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    //职位调整更新简历
    @RequestMapping("/updateResume")
    @ResponseBody
    public int updateResume(Resume resume) {
        try {
            userService.updateResume(resume);
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    //开除员工
    @RequestMapping("/expelEmployee")
    @ResponseBody
    public Integer expelEmployee(Integer uId, Integer rId) {
        try {
            managerService.expelEmployee(uId, rId);
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    //获取简历列表
    @RequestMapping("/findResumeList")
    @ResponseBody
    public List<Resume> findResumeList(Integer pId) {
        List<Resume> resumes = null;
        try {
            resumes = managerService.findResumeList(pId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resumes;
    }

    //获取部门员工列表
    @RequestMapping("/sectionEmployees")
    @ResponseBody
    public List<EntryTable> findEntryList(Manager manager) {
        CustomQueryVo customQueryVo = new CustomQueryVo();
        customQueryVo.setSectionId(manager.getSection().getId());
        customQueryVo.setDate(new Date());
        List<EntryTable> entryTables = null;
        try {
            entryTables = managerService.findEntryList(customQueryVo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return entryTables;
    }

    //获取上月工资列表（发放工资前）
    @RequestMapping("/salaryList")
    @ResponseBody
    public List<SalarySheet> salaryList(CustomQueryVo customQueryVo) {
        List<SalarySheet> salarySheets = null;
        try {
            salarySheets = managerService.getSalaryList(customQueryVo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return salarySheets;
    }

}
